<template>
    <PopList :title="'样式编辑器'" :showButton="true" @close="close" @ok="ok">
        <div class="model_style_box_content">
            <div class="model_content_top">
                <div class="model_style_textarea">
                    <textarea v-model="styleContent"></textarea>
                </div>
                <div class="model_style_footer">
                    <a href="https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification/Styling"
                        target="_blank">style语言说明</a>
                    <button @click="saveStyle">另存为新样式</button>
                    <button @click="useStyle">应用</button>
                </div>
            </div>

        </div>
        <div class="images_bottom_content">
            <div class="images_img_list">
                <div v-for="(item, index) in styleList" :id="item.id" class="images_img_lilist">
                    <div class="images_imgposition" :class="{ 'images_checkedactive': checkedactive == index }"
                        @click="changeStyle(item, index)" @contextmenu.prevent.stop="contexMenuEvent(item, index)">
                        <img :src="item.thumbnail" alt="">
                        <span v-show="iconIsShow == index ? true : false">{{ item.name }}</span>
                    </div>
                    <div class="images_onlineimageName" @mouseenter="handleMouseEnter(index)"
                        @mouseleave="handleMouseLeave" v-if="inputIndex !== index">
                        {{ item.name }}
                    </div>
                    <input class="model_content_right_input" type="text" v-model="inputValue" v-else
                        @blur="changeName(item, index)" @keyup="enter($event, item, index)" :key="index" ref="myInput">
                </div>
            </div>
        </div>
    </PopList>
    <ContextMenuCom :baseItems="menuContent"></ContextMenuCom>
</template>
<script setup lang="ts">
import { Message, messageBox } from "earthsdk-ui";
import { ES3DTileset } from "esobjs-xe2-plugin/dist-node/esobjs-xe2-plugin-main";
import { inject, onMounted, ref } from 'vue';
import { SceneTree } from 'xbsj-xe2/dist-node/xe2';
import { deleteApi, getNoToken, post, put } from '../../../api/service';
import PopList from "../../../components/PopList.vue";
import ContextMenuCom from '../../../components/commom/ContextMenuCom.vue';
import { XbsjEarthUi } from "../../../scripts/xbsjEarthUi";
const xbsjEarthUi = inject('xbsjEarthUi') as XbsjEarthUi
const sceneTree = inject('sceneTree') as SceneTree
type menuContentType = {
    text: string;
    keys: string;
    func: () => void;
} | {
    type: "divider",
}
const menuContent = ref<Array<menuContentType>>([])
const props = withDefaults(defineProps<{
    defaultStyle: string
}>(), {
});
const { defaultStyle } = props
const styleList = ref()
const styleContent = ref()
const checkedactive = ref()
const iconIsShow = ref()
const inputIndex = ref()
const inputValue = ref()
const contextmenuItem = ref()
const myInput = ref<HTMLElement>()

const emits = defineEmits(['close']);
//失去焦点
const changeName = (item: any, index: number) => {
    put(`${xbsjEarthUi.cesiumLabUrl}/other/rename/styles/${item._id}`, { name: inputValue.value }).then(res => {
    }).catch(error => {
        console.log(error);
    })
    updateList()
    inputIndex.value = null
}
//按键enter
const enter = (e: any, item: any, index: number) => {
    if (e.keyCode !== 13) return
    put(`${xbsjEarthUi.cesiumLabUrl}/other/rename/styles/${item._id}`, { name: inputValue.value }).then(res => {
    }).catch(error => {
        console.log(error);
    })
    updateList()
    inputIndex.value = null
}
const contexMenuEvent = (item: any, index: number) => {//元素右键
    contextmenuItem.value = item
    if (!item) return
    const baseItems: Array<menuContentType> = [
        {
            text: "重命名",
            keys: "",
            func: () => {
                inputIndex.value = index
                inputValue.value = item.name
            },
        },
        {
            text: "更新缩略图",
            keys: "",
            func: () => {
                messageBox({ text: '确认更新缩略图吗？' })
                    .then(() => {
                        updateConfirm()
                    })
                    .catch((err) => {
                    })
            },
        },
        {
            text: "删除",
            keys: "",
            func: () => {
                messageBox({ text: '确认删除？' })
                    .then(() => {
                        deleteConfirm()
                    })
                    .catch((err) => {
                    })
            },
        }
    ];
    menuContent.value = baseItems
}

//删除
const deleteConfirm = () => {
    // console.log(contextmenuItem.value);
    deleteApi(`${xbsjEarthUi.cesiumLabUrl}/style/${contextmenuItem.value._id}`).then(res => {
        // console.log(res);
        Message.success('删除成功')

    }).catch(error => {
        console.log(error);
    })
    updateList()
}

//更新缩略图
const updateConfirm = () => {
    // console.log(contextmenuItem.value);
    const viewer = xbsjEarthUi.activeViewer
    if (!viewer) return
    viewer.capture().then(res => {
        if (res) {
            put(`${xbsjEarthUi.cesiumLabUrl}/other/thumbnail/styles/${contextmenuItem.value._id}`, { thumbnail: res }).then(res => {
                // console.log(res);
                Message.success('更新成功')

            }).catch(error => {
                console.log(error);
            })
        }
    }).catch(error => {
        console.log(error);

    })
    updateList()
}
const close = () => {
    const lastSelectedItem = sceneTree.lastSelectedItem
    if (!lastSelectedItem) return
    if (lastSelectedItem.type === 'ES3DTileset') {
        const sceneObject = lastSelectedItem.sceneObject as ES3DTileset
        if (styleTransformJson(defaultStyle)) {
            sceneObject.czmStyleJson = styleTransformJson(defaultStyle)
        } else {
            sceneObject.czmStyleJson = styleTransformJson('var style={}')
        }
    }
    emits("close")
}
//样式转换成json
const styleTransformJson = (str: string) => {
    if (!str) return
    const f = new Function(`${str}; return style;`)
    return f()
}
const ok = () => {
    if (!styleContent.value) {
        Message.error('typeof style === "undefined"');
    }
    const lastSelectedItem = sceneTree.lastSelectedItem
    if (!lastSelectedItem) return
    if (lastSelectedItem.type === 'ES3DTileset') {
        const sceneObject = lastSelectedItem.sceneObject as ES3DTileset
        if (styleContent.value === '{}') {
            sceneObject.czmStyleJson = styleTransformJson('var style={}')
        } else if (styleTransformJson(styleContent.value)) {
            sceneObject.czmStyleJson = styleTransformJson(styleContent.value)
        }
    }
    emits("close", styleContent.value)
}
//另存为新样式
const saveStyle = () => {
    const viewer = xbsjEarthUi.activeViewer
    if (!viewer) return
    viewer.capture().then(res => {
        if (res) {
            const parms = {
                name: '新建样式',
                code: styleContent.value,
                thumbnail: res
            }
            post(`${xbsjEarthUi.cesiumLabUrl}/style`, parms).then(res => {
                // console.log(res);
            }).catch(error => {
                console.log(error);
                Message.error('Request failed with status code 500');
            })
            updateList()

        }
    }).catch(error => {
        console.log(error);

    })
}
const useStyle = () => {
    if (!styleContent.value) {
        Message.error('typeof style === "undefined"');
    }
    const lastSelectedItem = sceneTree.lastSelectedItem
    if (!lastSelectedItem) return
    if (lastSelectedItem.type === 'ES3DTileset') {
        const sceneObject = lastSelectedItem.sceneObject as ES3DTileset
        // console.log('sceneObject',sceneObject);
        if (styleTransformJson(styleContent.value)) {
            sceneObject.czmStyleJson = styleTransformJson(styleContent.value)
        }
    }
}
const changeStyle = (item: any, index: any) => {
    checkedactive.value = index
    styleContent.value = item.code
}
const handleMouseEnter = (index: number) => {
    iconIsShow.value = index
}
const handleMouseLeave = () => {
    iconIsShow.value = null
}
const updateList = () => {
    getNoToken(`${xbsjEarthUi.cesiumLabUrl}/style/?key=&sort=asc&sortfield=date`).then((res: any) => {
        if (res && res.styles) {
            // console.log(res);
            styleList.value = res.styles.rows
        }
    }).catch(error => {
        console.log(error);
    })
}
onMounted(() => {
    updateList()
    styleContent.value = defaultStyle
})

</script>
